<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<title></title>
		<link href="css/mui.min.css" rel="stylesheet" />
		<link href="css/style.css" rel="stylesheet" type="text/css">
		<style>
	
			.mui-btn {
				padding: 10px;
			}
			.ui-calendar {margin:50px 0;border-radius: 10px 10px 10px 10px;box-shadow: 2px 2px 20px 0; background-color:#FFF; position:relative;}
	        .ui-calendar caption,.ui-calendar th,.ui-calendar-cell-current a {background: url(images/sprite-calendar.png) repeat-x;}
	        .ui-calendar caption { height:26px; padding-top: 6px; text-align:left; font-family:Simsun; background-position: 0 -30px; border: 1px solid #861e1b;}
	        .ui-calendar caption a{ display:inline-block; margin:0 3px; padding: 0 2px; background-repeat: no-repeat; color: #FFF;}
	        .ui-calendar-selected-date,.ui-calendar-select {background-color:rgba(34,34,34,0.3);border-radius: 10px 10px 10px 10px;}
	        .ui-calendar-selected-date {  display:inline-block; padding:2px 10px; color:#FFF; position:relative; z-index:2;}
	        .ui-calendar-select {position: absolute; width: 104px; left: 51px; background-color:rgba(0,0,0,0.8); z-index:1;top:7px;display:none; padding:25px 0 10px 0;}
	        .ui-calendar-select li a{ height:25px; line-height:25px;text-align:center; display:block;color:#FFF; margin:0;}
	        .ui-calendar-select li a:hover{background-color:#222;}
	        .ui-calendar a {text-decoration:none;color:#4d4d4d;}
	        .ui-calendar th {color:#707687; height: 26px; background-position: 0 0;}
	        .ui-calendar th,.ui-calendar td {text-align:center;}
	        .ui-calendar th,.ui-calendar td {width:30px; height:30px; line-height:30px;}
	        .ui-calendar td a {display:block;}
	        .ui-calendar-cell-disabled {color:#c0c0c0;}
	        .ui-calendar-cell-current a{border-radius: 8px 8px 8px 8px; font-weight: bold;margin: 0 auto;background-position:20px -104px;background-repeat: no-repeat;width:28px; height:28px; color:#EA5454;}
	    	.mui-badge { 
	    		width: 14px;
	    		height: 14px;
                margin-right: -20px;
            } 
		</style>
	</head>

	<body>
		<header class="mui-bar mui-bar-nav" >
			<a class="mui-action-menu mui-icon mui-icon-bars mui-pull-left"></a>
			<a id="return_today" class="mui-icon mui-icon-undo mui-pull-right today" style="color: #999;"></a>
			<h1 class="mui-title">卉卉打卡</h1>
		</header>
		<div class="mui-content">
			<div id="container">
				<h5 class="mui-content-padded" style="margin: 15px 10px;text-align: right;">
				<span id="today_num"></span>&nbsp;
				<span id="events_day" ></span>
				<button id="hidden_button" style="display: none;"></button>
				<span id="current_month" style="display: none;"></span>	
				</h5>
				<div class="wrapper" id="wrapper">
					<div class="date_row date_week">
				        <div class="date_item">周日</div>
				        <div class="date_item">周一</div>
				        <div class="date_item">周二</div>
				        <div class="date_item">周三</div>
				        <div class="date_item">周四</div>
				        <div class="date_item">周五</div>
				        <div class="date_item">周六</div>
				    </div>
				    
				    <div class="slide_wrap">
				    	<div class="date_slide"> 
				            <div class="date_list" id="date_list_0">
				            </div><!--date_list-->
				            
				            <div class="date_list" id="date_list_1">
				            </div><!--date_list-->
				        </div>
				    </div>
				    <h5 class="mui-content" style="margin: 15px 12px;text-align: right;">打卡内容</h5>
			    	<ul class="mui-table-view" id="combo_indexlist">
						<li class="mui-table-view-cell">
							<span>按菜单键进入打卡内容管理进行添加</span>
							<!--<div class="mui-switch mui-switch-blue mui-switch-mini mui-active">
								<div class="mui-switch-handle"></div>
							</div>-->
						</li>
					</ul>
					
				    <!--date_info-->
				</div>
	    	</div>
		</div>
		<script src="js/mui.min.js"></script>
		<script src="js/app.js"></script>
		<script type="text/javascript" src="js/zepto.min.js"></script>
		<script type="text/javascript" src="js/hammer.min.js"></script>
		<script type="text/javascript" src="js/jquery.hammer.min.js"></script>
		<script type="text/javascript" src="js/LunarCalendar.min.js"></script>
		<script type="text/javascript" src="js/calendar.js"></script>
		<script src="js/main.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/md5.min.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/array.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/message.js" type="text/javascript" charset="utf-8"></script>
		<script>
			var menu = null,
				main = null;
			var showMenu = false;
			var app_init_date = parseDate(new Date())
			mui.init({
				swipeBack: false,
				statusBarBackground: '#f7f7f7',
				gestureConfig: {
					doubletap: true
				},
			});
			mui('.mui-content .mui-switch').each(function() { //循环所有toggle
				//toggle.classList.contains('mui-active') 可识别该toggle的开关状态
				//this.parentNode.querySelector('span').innerText = '状态：' + (this.classList.contains('mui-active') ? 'true' : 'false');
				/**
				 * toggle 事件监听
				 */
				this.addEventListener('toggle', function(event) {
					
					//开关事件入口
					//event.detail.isActive 可直接获取当前状态
					//this.parentNode.querySelector('span').innerText = '状态：' + (event.detail.isActive ? 'true' : 'false');
				});
			});
			mui.plusReady(function() {
				
				var lauchFlag = plus.storage.getItem("lauchFlag")
				if(!lauchFlag){
					plus.webview.open("guide.html")
				}
				
				//初始化数据库
				initialize();
				
				//仅支持竖屏显示
				plus.screen.lockOrientation("portrait-primary");
				main = plus.webview.currentWebview();
				main.addEventListener('maskClick', closeMenu);
				//处理侧滑导航，为了避免和子页面初始化等竞争资源，延迟加载侧滑页面；
				setTimeout(function() {
					menu = mui.preload({
						id: 'index-menu',
						url: 'index-menu.html',
						styles: {
							left: 0,
							width: '70%',
							zindex: -1
						},
						show: {
							aniShow: 'none'
						}
					});
				}, 200);
				
				initLoad();
				
			});
			var isInTransition = false;
			/**
			 * 显示侧滑菜单
			 */
			function openMenu() {
				if (isInTransition) {
					return;
				}
				if (!showMenu) {
					//侧滑菜单处于隐藏状态，则立即显示出来；
					isInTransition = true;
					menu.setStyle({
						mask: 'rgba(0,0,0,0)'
					}); //menu设置透明遮罩防止点击
					menu.show('none', 0, function() {
						//主窗体开始侧滑并显示遮罩
						main.setStyle({
							mask: 'rgba(0,0,0,0.4)',
							left: '70%',
							transition: {
								duration: 150
							}
						});
						mui.later(function() {
							isInTransition = false;
							menu.setStyle({
								mask: "none"
							}); //移除menu的mask
						}, 160);
						showMenu = true;
					});
				}
			};
			/**
			 * 关闭菜单
			 */
			function closeMenu() {
				if (isInTransition) {
					return;
				}
				if (showMenu) {
					//关闭遮罩；
					//主窗体开始侧滑；
					isInTransition = true;
					main.setStyle({
						mask: 'none',
						left: '0',
						transition: {
							duration: 200
						}
					});
					showMenu = false;
					//等动画结束后，隐藏菜单webview，节省资源；
					mui.later(function() {
						isInTransition = false;
						menu.hide();
					}, 300);
					initLoad();
				}
			};
			//点击左上角侧滑图标，打开侧滑菜单；
			document.querySelector('.mui-action-menu').addEventListener('tap', function(e) {
				if (showMenu) {
					closeMenu();
				} else {
					openMenu();
				}
			});
			//敲击顶部导航，内容区回到顶部
/*			document.querySelector('header').addEventListener('doubletap', function() {
				main.children()[0].evalJS('mui.scrollTo(0, 100)');
			});*/
			//主界面向右滑动，若菜单未显示，则显示菜单；否则不做任何操作
			//window.addEventListener("swiperight", openMenu);
			document.getElementById('combo_indexlist').addEventListener("swiperight", openMenu);
			//主界面向左滑动，若菜单已显示，则关闭菜单；否则，不做任何操作；
			window.addEventListener("swipeleft", closeMenu);
			//侧滑菜单触发关闭菜单命令
			window.addEventListener("menu:close", closeMenu);
			window.addEventListener("menu:open", openMenu);
			//重写mui.menu方法，Android版本menu按键按下可自动打开、关闭侧滑菜单；
			mui.menu = function() {
					if (showMenu) {
						closeMenu();
					} else {
						openMenu();
					}
				}
				//处理右上角关于图标的点击事件；
			var subWebview = null,
				template = null;
			//首页返回键处理
			//处理逻辑：1秒内，连续两次按返回键，则退出应用；
			var first = null;
			mui.back = function() {
				if (showMenu) {
					closeMenu();
				}else if(!isToday()){
					var el = document.getElementById('return_today');
					mui.trigger(el,'tap');
				}
				else {
					//首次按键，提示‘再按一次退出应用’
					if (!first) {
						first = new Date().getTime();
						mui.toast('再按一次退出应用');
						setTimeout(function() {
							first = null;
						}, 1000);
					} else {
						if (new Date().getTime() - first < 1000) {
							plus.runtime.quit();
						}
					}
				}
			};
			
			
			//是不是今天
			function isToday(){
				var date = document.getElementById("today_num").innerText;
				var res = parseDate(new Date());
				if(res == date){
					return true;
				}else{
					return false;
				}
				
			}

			document.addEventListener('plusready',function(){
			    checkArguments();
			    // 监听点击消息事件
				plus.push.addEventListener( "click", function( msg ) {
					clearAllPush();
					// 判断是从本地创建还是离线推送的消息
					switch( msg.payload ) {
						case "LocalMSG":
							initLoad();
						break;
						default:
							initLoad();
						break;
					}
					// 提示点击的内容
					//plus.nativeUI.alert( msg.content );
					// 处理其它数据
				}, false );
				// 监听在线消息事件
				plus.push.addEventListener( "receive", function( msg ) {
					if ( msg.aps ) {  // Apple APNS message
						//outSet( "接收到在线APNS消息：" );
					} else {
						//outSet( "接收到在线透传消息：" );
					}
				}, false );
			},false);
			// 判断启动方式
			function checkArguments(){
			    var args = plus.runtime.arguments;
			    if(args){
			        // 处理args参数，如打开新页面等
			        console.log("args:"+args);
			    }
			}
			// 处理从后台恢复
			document.addEventListener('newintent',function(){
			    checkArguments();
			    initLoad();
			},false);
			
			
			var backgroundTime = 0;
			var interID;
			
	        // 监听从前台切换到后台事件
		    document.addEventListener("pause",function(){
		        backgroundTime = Math.round(new Date().getTime()/1000);
		        interID = setInterval(checkSign,1000*60*60*2);
		        //interID = setInterval(checkSign,1000*2);
		    }, false );
		    
		    // 监听从后台切换回前台事件
		    document.addEventListener("resume",function(){
		        var nowTime = Math.round(new Date().getTime()/1000);
		        // 如果程序退出到后台时间超过20秒，则重新要求输入手势密码
		        if (backgroundTime != 0) {
		            if (nowTime - backgroundTime > 20) {
		            	//return_today
		            	var el = document.getElementById('return_today');
						mui.trigger(el,'tap');
						var thisMonth = parseMonth(document.getElementById("today_num").innerText);
		   				//signCounts(thisMonth,eventsCallback);
						//回到程序日期增加的情况
						var back_today = parseDate(new Date());
						if(back_today != app_init_date){
							//Calendar.init();
							window.location.reload();
							//initLoad()
							var el = document.getElementById('return_today');
							mui.trigger(el,'tap');
							
						}
		            }
		            
		            //清理掉定时任务
		            clearInterval(interID);
		        }
		    }, false );
		    
		    //change事件
			$("#today_num").on('change',function(){
				
				if(isToday()){
					initLoad();
				}else{
					eventsForDate(getTodayNum(),eventsCallback);
				}
				
				var thisMonth = parseMonth(document.getElementById("today_num").innerText);
		   		//signCounts(thisMonth,eventsCallback);
			})
		   
		   /**
		   $("#current_month").on('change',function(){
		   		var thisMonth = parseMonth(document.getElementById("today_num").innerText);
		   		signCounts(thisMonth,eventsCallback);
		   	})
		   
		   $("#return_today").on('tap',function(){
		   		var thisMonth = parseMonth(document.getElementById("today_num").innerText);
		   		signCounts(thisMonth,eventsCallback);
		   	})
		   **/
		   function getTodayNum(){
		   		return document.getElementById("today_num").innerText;
		   }
		   
		   //初始化打卡开关
		   function initSwitch(){
		   	mui('.mui-content .mui-switch').each(function() { //循环所有toggle
				/**
				 * toggle 事件监听
				 */
				//console.log(this.parentNode.querySelector('span').innerText);
				this.addEventListener('toggle', function(event) {
					var cname = this.parentNode.querySelector('span').innerText;
					//开关事件入口
					if(event.detail.isActive){
						insertData(cname,parseDate(new Date()),new Date().getTime());
						//重新计算今天的打卡量
						signCounts(parseDate(new Date()),parseDate(new Date()),eventsCallback);						
					}else{
						deleteData(cname,parseDate(new Date()));
						//重新计算今天的打卡量
						signCounts(parseDate(new Date()),parseDate(new Date()),eventsCallback);
					}
				});
			});
		   }
		   
		   
		   var eventsCallback ={
/*		   		active: function(cname){
		   			mui('.mui-content .mui-switch').each(function() { //循环所有toggle
					//toggle.classList.contains('mui-active') 可识别该toggle的开关状态
					var thiscname = this.parentNode.querySelector('span').innerText;// = '状态：' + (this.classList.contains('mui-active') ? 'true' : 'false');
						if(thiscname == cname){
							this.className += "mui-switch-active";
						}
					});
			   	},*/
			   	init: function(htmls){
		   			document.getElementById("combo_indexlist").innerHTML = htmls;
				    //mui('.mui-content .mui-switch')['switch']();
				    //initSwitch();
		   		},
		   		
		   		combo: function(comboList){
		   			
		   			var eventList = new Array();
		   			mui('.mui-content .mui-switch').each(function() {
						var thisctitle = this.parentNode.querySelector('span').innerText;
						eventList.push(thisctitle)
					});
					
					//数组比较
					
					var minList = Array.complement(comboList,eventList);
					var htmls = "";
					for (i = 0; i < minList.length; i++){
				    	htmls += '<li class="mui-table-view-cell">'+
							'<span>'+ minList[i]+ '</span>'+
							'<div class="mui-switch mui-switch-blue mui-switch-mini">'+
								'<div class="mui-switch-handle"></div>'+
							'</div>'+
						'</li>';
						
					}
					if(comboList.length == 0 && eventList.length == 0){
						document.getElementById("combo_indexlist").innerHTML = '<li class="mui-table-view-cell">点击左上角或按菜单键进入打卡内容管理进行添加</li>';
					}else if(comboList.length != 0 && eventList.length == 0){
						document.getElementById("combo_indexlist").innerHTML = htmls;
					}else if(comboList.length == 0 && eventList.length != 0) {
						//document.getElementById("combo_indexlist").innerHTML += htmls;
					}else{
						document.getElementById("combo_indexlist").innerHTML += htmls;
					}
					mui('.mui-content .mui-switch')['switch']();
					initSwitch()
					
		   	},
		   	//<span class="mui-badge mui-badge-success" id="2016-06-28">1</span>
		   	signcounts: function(signArray){
		   		/*document.getElementById(parseDate(new Date())).className = " ";
		   		$("#"+parseDate(new Date())).hide();
		   		for(var i = 0, l = signArray.length; i < l; i++){
		   			var date = signArray[i].name;
		   			var counts = signArray[i].value;
		   			
		   			if(counts && date != undefined ){
		   				document.getElementById(date).innerText = counts>9?"9+":counts;
		   				document.getElementById(date).className+=" mui-badge mui-badge-success";
		   				$("#"+date).show();
		   			}
		   			
		   			
		   		}*/
		   	}
		   	
		   }
		   
		   function initLoad(){
		   	if(isToday()){
		   		//加载eventlist
				eventsForDate(parseDate(new Date()),eventsCallback);
				//加载今天的combolist
				loadCombo(eventsCallback);
				mui('.mui-content .mui-switch')['switch']();
			}
		   	
		   }
		   
		   
		   function checkSign(){
		   	var checkday = parseDate(new Date());
		   	var hour = new Date().getHours();
		   	//指定在规定的时间范围内才提醒
		   	if(hour < 19 || hour > 22){
		   		return;
		   	}
		   	checkTodaySign(checkday);
		   	
		   	
		   }
		</script>
	</body>

</html>